package lanxing.bootstrap.json;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import lanxing.chances.util.JSONUtils;

/**
 * @author <a href="mailto:lanxing@chances.com.cn">lanxing</a>
 * @version 2019年7月13日
 *
 */
@Component
public class LoadTextData {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${data.json:data}")
    private String dataFolder;

    private Map<String, Object> textDataMap;

    @PostConstruct
    public void initData() throws FileNotFoundException {
        loadJsonData();
    }

    public void loadJsonData() throws FileNotFoundException {
        textDataMap = new HashMap<>();

        File jsonFolderFile = ResourceUtils.getFile(dataFolder);
        File[] jsonFiles = jsonFolderFile.listFiles();
        for (File file : jsonFiles) {
            String jsonString = getJsonDataString(file);

            if (jsonString.startsWith("[")) {
                List<Map<String, Object>> jsonObject = JSONUtils.toArray(jsonString);
                textDataMap.put(file.getName(), jsonObject);
            } else if (jsonString.startsWith("{")) {
                Map<String, Object> jsonObject = JSONUtils.toMap(jsonString);
                textDataMap.put(file.getName(), jsonObject);
            } else {
                textDataMap.put(file.getName(), jsonString);
            }
        }
    }

    private String getJsonDataString(File file) {
        BufferedReader br = null;
        StringBuffer message = new StringBuffer();
        String line = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            while ((line = br.readLine()) != null) {
                message.append(line);
            }
            String jsonString = message.toString();
            logger.info("\r\npath:{},\r\njson:{}", file.getPath(), jsonString);
            return jsonString.trim();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Map<String, Object> getTextDataMap() {
        return textDataMap;
    }
}
